import React, { useEffect, useState } from 'react'
import { useSearchParams, useNavigate, useLocation } from 'react-router-dom'
import http from '../../api'
import DetailBottomNav from '../../components/publicComponents/DetailBottomNav'
import DetailTopNav from '../../components/publicComponents/DetailTopNav'
import Banner from '../../components/Detaile/CircleDetail/Banner'
import BetterItem from '../../components/Detaile/CircleDetail/BetterItem'
import GoodThingItem from '../../components/Detaile/CircleDetail/GoodThingItem'
import CommentItem from '../../components/Detaile/CircleDetail/CommentItem'
import { CircleDetailResult, CircleMaterialList, CircleReplyList, CircleReplyResult, CircleSpuList, CircleStoreList, CircleUser, UserList } from '../../myTypes'
import style from './index.module.css'
import { Toast } from 'antd-mobile'
import Loading from '../../components/publicComponents/Loading'

export interface CurData {
  address: string
  area: string
  collect: number
  containVideo: number
  content: string
  createTime: string
  updateTime: string
  userId: string
  title: string
  type: string
  id: string
  headFigure: string
  isWrap: number
  forward: number
  love: number
  replyNum: number
  merchantId: string
  collectStatus: number
}
interface LoveParamsType {
  userId: string
  circleId: string
  authorId: string
  type: string | null
  title: string
  content: string
  headfigure: string
  area: string
  authorName: string
  avatar: string
}
export interface AttentionParams {
  userId: string
  attentionUserId: string
  fanType: string | null
  followerType: string | null
  isWrap: number
}

export interface CommentParams {
  circleId: string | undefined
  receiverId: string | undefined
  senderId: string | undefined
  isWrap: number | undefined
  status: number | undefined
  receiverType: string | undefined | null
  senderType: string | undefined
}

export default function CircleDetail() {
  const [search] = useSearchParams()
  const circleId = search.get('circleid') as string
  const type = useLocation().state.type as string
  const navigate = useNavigate()
  let [id, setId] = useState('')
  // 提到的好去处
  const [circleStoreList, setCircleStoreList] = useState<Array<CircleStoreList>>([])
  // 作者信息
  const [circleUser, setCircleUser] = useState<CircleUser>()
  // 轮播图数据
  const [circleMaterialList, setCircleMaterialList] = useState<Array<CircleMaterialList>>([])
  // 当前活动的数据
  const [curCircleData, setCircleData] = useState<CurData>()
  // 提到的好物数据
  const [circleSpuList, setCircleSpuList] = useState<Array<CircleSpuList>>([])
  // 评论
  const [circleReplyList, setCircleReplyList] = useState<Array<CircleReplyList>>([])
  const [replyNum, setReplyNum] = useState(0)
  const [userInfo, setUserInfo] = useState<Array<UserList>>([])
  const [loveList, setLoveList] = useState<Array<string>>([])
  const [attentionParams, setAttentionParams] = useState<AttentionParams>()

  // 点击喜欢和取消喜欢参数数据
  const [loveParams, setLoveParams] = useState<LoveParamsType>()
  // 发表评论请求参数
  const [commentParams, setCommentParams] = useState<CommentParams>()

  useEffect(() => {
    // 获取用户id判断是否登录
    const userId = localStorage.getItem('userId')
    if (userId) {
      id = userId
      requestCurCircleData()
      setId(userId)
      Toast.show({
        content: '加载中...',
        maskClickable: false,
        duration: 0,
        icon: <Loading />
      })
    } else {
      navigate('/login')
    }
  }, [])

  function createObj(circleData: CircleDetailResult) {
    return {
      address: circleData.address,
      area: circleData.area,
      collect: circleData.collect,
      containVideo: circleData.containVideo,
      content: circleData.content,
      createTime: circleData.createTime,
      updateTime: circleData.updateTime,
      userId: circleData.userId,
      title: circleData.title,
      type: circleData.type,
      id: circleData.id,
      headFigure: circleData.headFigure,
      isWrap: circleData.isWrap,
      forward: circleData.forward,
      love: circleData.love,
      replyNum: circleData.replyNum,
      merchantId: circleData.merchantId,
      replyNNum: circleData.replyNum,
      collectStatus: circleData.collectStatus
    }
  }

  async function requestCurCircleData() {
    let url = ''
    let params = {}
    if (type !== 'comment') {
      url = '/mty/circle/get'
      params = {
        accountId: id,
        circleId: circleId
      }
    } else {
      url = '/mty/comment/getDetail'
      params = {
        accountId: id,
        commentId: circleId
      }
    }
    const data = await http('get', url, params)

    Toast.clear()
    if (data) {
      const circleData = data.data as CircleDetailResult
      if (!circleData.address) {
        navigate(-1)
        return
      }

      setUserInfo(circleData.circleReplyResult.userList)
      setReplyNum(circleData.replyNum)
      setLoveList(circleData.circleReplyResult.loveList)
      // 点击喜欢请求参数
      setLoveParams({
        userId: id,
        circleId: circleData.id,
        authorId: circleData.circleUser.id,
        type: circleData.circleUser.type,
        title: circleData.title,
        content: '',
        headfigure: circleData.headFigure,
        area: circleData.area,
        authorName: circleData.circleUser.name,
        avatar: circleData.circleUser.head
      })
      setAttentionParams({
        userId: id,
        attentionUserId: circleData.circleUser.id,
        fanType: circleData.circleReplyResult.userList[0]?.type || 'c',
        followerType: circleData.circleUser.type,
        isWrap: circleData.isWrap
      })
      // 发布评论请求参数
      setCommentParams({
        circleId: circleData.id,
        receiverId: circleData.circleUser.id,
        senderId: id,
        isWrap: circleData.isWrap,
        status: circleData.status,
        receiverType: circleData.circleUser.type,
        senderType: circleData.circleReplyResult.userList[0]?.type
      })
      setCircleStoreList(circleData.circleStoreList)
      setCircleUser(circleData.circleUser)
      setCircleMaterialList(circleData.circleMaterialList)
      setCircleData(createObj(circleData))
      setCircleSpuList(circleData.circleSpuList)
      setCircleReplyList(circleData.circleReplyResult.circleReplyList)
    } else {
      Toast.show({
        content: '该圈子已删除',
        duration: 1000,
        afterClose: () => {
          navigate(-1)
        }
      })
    }
  }

  //#region 喜欢和取消喜欢
  async function requestLove() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('post', '/mty/circleLove/love', {
      userId: id,
      circleId: loveParams?.circleId,
      authorId: loveParams?.authorId,
      type: loveParams?.type,
      title: loveParams?.title,
      content: loveParams?.content,
      headfigure: loveParams?.headfigure,
      area: loveParams?.area,
      authorName: loveParams?.authorName,
      avatar: loveParams?.avatar
    })
    if (data && data.code === 200) {
      Toast.clear()
      Toast.show({
        content: '谢谢你的喜欢',
        duration: 2000
      })
      requestCurCircleData()
    } else {
      Toast.clear()
      Toast.show({
        content: data?.msg,
        duration: 2000
      })
    }
  }
  async function requestDelLove() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('delete', '/mty/circleLove/del', {
      circleId: loveParams?.circleId,
      userId: loveParams?.userId,
      type: loveParams?.type
    })
    if (data && data.code === 200) {
      requestCurCircleData()
    } else {
      Toast.clear()
      Toast.show({
        content: data?.msg,
        duration: 2000
      })
    }
  }
  //#endregion

  // 获取评论
  async function getCommendData() {
    const result = await http('get', '/mty/circleReply/getAll', {
      pageNum: 1,
      pageSize: 10,
      circleId: curCircleData?.id,
      pid: curCircleData?.id,
      accountId: id
    })
    if (result && result.code === 200) {
      const data = result.data as CircleReplyResult
      setCircleReplyList(data.circleReplyList)
      const total = data.total as number
      setReplyNum(total)
      setUserInfo(data.userList)
      setLoveList(data.loveList)
    }
  }
  return (
    <div style={{ paddingTop: '50px', paddingBottom: '60px' }}>
      {/* 顶部导航 */}
      <DetailTopNav circleUser={circleUser} attentionParams={attentionParams} />

      {/* 轮播图 */}
      <Banner circleMaterialList={circleMaterialList} area={curCircleData?.area} />

      {/* 标题和描述 */}
      <div className={style.describe}>
        <div className={style.title}>{curCircleData?.title}</div>
        <div className={style.desc}>{curCircleData?.content}</div>
        <div className={style.update}>{curCircleData?.updateTime.slice(0, 10)}</div>
      </div>

      {/* 评论 */}
      {circleReplyList.length > 0 && (
        <div className={style['comment-container']}>
          <div className={style['comment-list']}>
            {circleReplyList.map((reply, i) => (
              <CommentItem style={style} key={i} reply={reply} userInfo={userInfo[0]} loveList={loveList} getCommendData={getCommendData} accountId={commentParams?.senderId} circleId={circleId} />
            ))}
            <div className={style['comment-count']}>共{circleReplyList.length}条评论</div>
          </div>
        </div>
      )}
      {/* 提到的好物 */}
      {circleSpuList.length > 0 && (
        <div className={style['better-container']}>
          <div className={style['better-title']}>提到的好物</div>
          <div className={style['better-list']}>
            {circleSpuList.map((item) => (
              <GoodThingItem item={item} style={style} key={item.id} />
            ))}
          </div>
        </div>
      )}

      {/* 提到好去处 */}
      {circleStoreList.length > 0 && (
        <div className={style['better-container']}>
          <div className={style['better-title']}>提到的好去处</div>
          <div className={style['better-list']}>
            {circleStoreList.map((item) => (
              <BetterItem item={item} style={style} key={item.id} />
            ))}
          </div>
        </div>
      )}
      {/* 底部导航 */}
      <DetailBottomNav type={type} replyNum={replyNum} curData={curCircleData} requestLove={requestLove} requestDelLove={requestDelLove} commentParams={commentParams} getCommendData={getCommendData} />
    </div>
  )
}
